package com.wwwarehouse.carddesk.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.GridView;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.carddesk.R;
import com.wwwarehouse.carddesk.adapter.TaskDetailsAdapter;
import com.wwwarehouse.carddesk.constant.CardDeskConstant;
import com.wwwarehouse.carddesk.utils.TaskRouterUtils;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CardDeskTaskResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.bean.response.GetImportToolIndexBean;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tools.ScreenUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.wwwarehouse.carddesk.fragment.TaskTabFragment.KEY_TASK_ORDER_SORT;
import static com.wwwarehouse.carddesk.fragment.TaskTabFragment.KEY_TASK_ORDER_TYPE;
import static com.wwwarehouse.carddesk.fragment.TaskTabFragment.KEY_TASK_PAGE;
import static com.wwwarehouse.carddesk.fragment.TaskTabFragment.KEY_TASK_SEARCH_TEXT;
import static com.wwwarehouse.carddesk.fragment.TaskTabFragment.KEY_TASK_TAG_SET;
import static com.wwwarehouse.carddesk.fragment.TaskTabFragment.LIMIT;

/**
 * Created by Jackie on 2017/8/17.
 * 卡片桌面任务卡片
 */

public class TaskDetailsFragment extends BaseFragment  {
    private View mRootView;
    private StateLayout mStateLayout;
    private GridView mGridView;
    private TaskDetailsAdapter mAdapter;

    private String mOrderSort;
    private String mOrderType;
    private String mSearchText;
    private Set<String> mTaskTagSet;
    private int mPage = 0;

    private CardDeskTaskResponseBean.TaskBean mTaskDetailsBean;

    private ImportResourceReceiver mImportResourceReceiver;

    private static final int REQUEST_GET_TASK_INFO = 0;
    private static final int REQUEST_IMPORT_ITEM_RESOURCE = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_task_details, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initEvent();
    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        if (enter) {
            getTaskInfo();
        }

        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mActivity.unregisterReceiver(mImportResourceReceiver);
    }

    private void initView() {
        mStateLayout = findView(mRootView, R.id.sl_layout);
        mGridView = findView(mRootView, R.id.gv_details);

        Bundle bundle = getArguments();
        if (bundle != null) {
            mOrderSort = bundle.getString(KEY_TASK_ORDER_SORT);
            mOrderType = bundle.getString(KEY_TASK_ORDER_TYPE);
            mSearchText = bundle.getString(KEY_TASK_SEARCH_TEXT);
            mTaskTagSet = (Set<String>) bundle.getSerializable(KEY_TASK_TAG_SET);
            mPage = bundle.getInt(KEY_TASK_PAGE);
        }

        IntentFilter intentFilter = new IntentFilter(TaskRouterUtils.ACTION_IMPORT_RESOURCE);
        mImportResourceReceiver = new ImportResourceReceiver();
        mActivity.registerReceiver(mImportResourceReceiver, intentFilter);
    }

    private void initEvent() {
    }

    @Override
    public void setTitle() {

    }

    @Override
    public void requestDatas() {

    }

    private void getTaskInfo() {
        mStateLayout.showProgressView(false);

        Map map = new HashMap<>();

        map.put("limit", LIMIT);
        map.put("page", mPage);
        map.put("orderSort", mOrderSort);
        map.put("orderType", mOrderType);
        map.put("searchText", mSearchText);
        map.put("taskTags", mTaskTagSet);

        NoHttpUtils.httpPost(CardDeskConstant.URL_GET_TASK_INFO, map, mOnResponseListener, REQUEST_GET_TASK_INFO);
    }

    /**
     * 导入物和资源
     */
    private void importItemResource() {
        Map map = new HashMap<>();
        map.put("businessUnitId", mTaskDetailsBean.getBelongBusiness());
        map.put("operationUkid", mTaskDetailsBean.getCardUkid());

        NoHttpUtils.httpPost(Constant.GET_IMPORT_TOOLS_INDEX, map, mOnResponseListener, REQUEST_IMPORT_ITEM_RESOURCE);
    }

    NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case REQUEST_GET_TASK_INFO:
                    if ("0".equals(commonClass.getCode())) {
                        CardDeskTaskResponseBean cardDeskTaskResponseBean = JSON.parseObject(commonClass.getData().toString(), CardDeskTaskResponseBean.class);
                        final List<CardDeskTaskResponseBean.TaskBean> taskDetailsList = cardDeskTaskResponseBean.getTasks();

                        int screenHeight = ScreenUtils.getScreenHeight(mActivity);
                        int statusHeight = ScreenUtils.getStatusHeight(mActivity);

                        int itemHeight = (screenHeight - statusHeight - ConvertUtils.dip2px(mActivity, 110)) / 3;

                        mAdapter = new TaskDetailsAdapter(mActivity, taskDetailsList, itemHeight);
                        mGridView.setAdapter(mAdapter);

                        //所有卡片的跳转事件
                        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                mTaskDetailsBean = taskDetailsList.get(position);
                                String taskType = mTaskDetailsBean.getTaskType();

                                Bundle bundle = new Bundle();
                                bundle.putSerializable(Constant.KEY_CARD_DESK_TASK_DETAILS, mTaskDetailsBean);

                                //跳转页面
                                TaskRouterUtils.goTask((BaseCardDeskActivity) mActivity, taskType, bundle);
                            }
                        });
                    } else {
                        mStateLayout.showSystemView(commonClass.getMsg(), false);
                        mStateLayout.setSystemListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mStateLayout.showProgressView(false);

                                getTaskInfo();
                            }
                        });
                    }
                    break;
                case REQUEST_IMPORT_ITEM_RESOURCE:
                    GetImportToolIndexBean getImportToolIndexBean = JSON.parseObject(commonClass.getData().toString(), GetImportToolIndexBean.class);
                    if (getImportToolIndexBean != null) {
                        if (getImportToolIndexBean.getPageType() == 1) {
                            //跳转到生成短链接的页面
                            Bundle bundle = new Bundle();
                            bundle.putString(Constant.KEY_INTENT_IMPORT_TYPE, mTaskDetailsBean.getTaskType());
                            bundle.putSerializable(Constant.KEY_INTENT_IMPORT_TOOL, getImportToolIndexBean);
                            pushFragment(CardDeskConstant.PATH_IMPORT_HAVE_SORT, bundle);
                        } else if (getImportToolIndexBean.getPageType() == 2) {
                            //跳转到时间页面
                            Bundle bundle = new Bundle();
                            bundle.putString(Constant.KEY_INTENT_IMPORT_TYPE, mTaskDetailsBean.getTaskType());
                            bundle.putSerializable(Constant.KEY_INTENT_IMPORT_TIME,  getImportToolIndexBean);
                            pushFragment(CardDeskConstant.PATH_DURATION_TIME, bundle);
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
            mStateLayout.showNetworkView(false);
            mStateLayout.setNetworkListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mStateLayout.showProgressView(false);

                    getTaskInfo();
                }
            });
        }

        @Override
        public void onFinish(int what) {
            mStateLayout.showContentView();
        }
    };

    private class ImportResourceReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            abortBroadcast();  //收到之后就中断广播，防止广播收到多次

            String action = intent.getAction();

            if (TaskRouterUtils.ACTION_IMPORT_RESOURCE.equals(action)) {
                Bundle bundle = intent.getExtras();
                mTaskDetailsBean = (CardDeskTaskResponseBean.TaskBean) bundle.getSerializable(Constant.KEY_CARD_DESK_TASK_DETAILS);

                importItemResource();
            }
        }
    }
}
